package com.sm.scorpio.http;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.scorpio.baselibrary.PoorApplication;
import com.scorpio.baselibrary.utils.AppDataUtil;
import com.scorpio.baselibrary.utils.DeviceIdUtil;
import com.sm.scorpio.ui.bean.model.UserBean;

import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * created by zhud on 2019/8/14
 */
public class HttpUtils {
    public static HttpApi postString() {
        return postString("");
    }

    public static HttpApi postString(JSONObject json) {
        return postString(json.toJSONString());
    }

    public static HttpApi postString(String jsonString) {
        final String requestEntity = TextUtils.isEmpty(jsonString) ? "" : jsonString;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(12, TimeUnit.SECONDS)
                .readTimeout(12, TimeUnit.SECONDS)
                .writeTimeout(12, TimeUnit.SECONDS)
                .addInterceptor(chain -> {
                    UserBean userBean = (UserBean) AppDataUtil.getInstance().readData(new UserBean());
                    Request.Builder builder = chain.request().newBuilder()
                            .header("uniqueId", DeviceIdUtil.getDeviceId(PoorApplication.getInstance()))
                            .addHeader("accountToken", userBean.accountToken == null ? "" : userBean.accountToken)
                            .addHeader("Content-Type", "application/json;charset=UTF-8")
                            .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), requestEntity));
                    return chain.proceed(builder.build());
                }).build();
        Retrofit retrofit = new Retrofit.Builder()
                //设置网络请求的Url地址
                .baseUrl(PoorApplication.getInstance().getHost())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        return retrofit.create(HttpApi.class);
    }
}
